package com.xx.springboot.controller;


import com.xx.springboot.entity.Student;
import com.xx.springboot.utils.XlsUtils;
import jxl.common.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
/**
 * @author: xiaoxi
 * @description: 导出 excel
 */
@Controller
public class ExportController {

    private Logger logger = Logger.getLogger(ExportController.class);

    @Autowired
    private XlsUtils xlsUtils;

    /**
     * @param response rep
     * @param fileName 导出的文件的名称
     * @param model    导出的后台配置模版
     * @param list     要导出的数据
     * @throws Exception ex
     */
    public void doExport(HttpServletRequest request, HttpServletResponse response, String fileName, String model, List list) throws Exception {
        // 生成要下载的文件
        String agent = request.getHeader("USER-AGENT");  //识别浏览器信息
        File outputXls = xlsUtils.outputXls(fileName, model, list, false);
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        if (agent != null && agent.contains("Firefox")) {// Firefox
            String enableFileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            response.setHeader("Content-Disposition", "attachment; filename=" + enableFileName);
        } else { //IE7+
            String enableFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName=" + enableFileName);
        }
        try {
            InputStream in = new FileInputStream(outputXls);
            OutputStream os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            do {
                length = in.read(b);
                os.write(b);
            } while (length > 0);
            os.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new Exception(e.getMessage());
        }
    }

    @GetMapping("/export")
    public void export(HttpServletRequest request, HttpServletResponse response){
        List<Student> list = new ArrayList<>();

        Student student = new Student();
        student.setId(new Long(1));
        student.setCupSize("1");
        student.setSize(100);
        list.add(student);

        try {
            doExport(request, response, "代理商.xls", "student", list );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
